

<template>
  <div class="main-container">
    <el-dialog v-model="dialogFormVisible" v-if="dialogFormVisible" title="添加资产" width="58%">
      <Add :departmentdata="departmentdata" :assetForm="assetForm" @addSubmit="handleSubmit"></Add>
    </el-dialog>
    <div class="table-actions">
      <el-button type="primary" @click="handleAdd">新增</el-button>
      <el-button type="warning" @click="handleEdit">修改</el-button>
      <el-button type="danger" @click="handleDelete">删除</el-button>
      <el-button @click="resetDateFilter">重置日期筛选</el-button>
      <el-button @click="clearFilter">重置筛选</el-button>
    </div>
    <el-table ref="tableRef" v-loading="loading" element-loading-text="数据加载中..." row-key="date" border :data="tableData" style="width: 100%;height: 50%;" highlight-current-row=true
      @row-click="handleRowClick"
     >
      <el-table-column prop="id" label="id" width="50"/>
      <el-table-column prop="assetCode" label="资产编号" width="120"/>
      <el-table-column prop="assetName" label="资产名称" width="120"/>
      <el-table-column prop="category" label="资产类型" width="100" />
      <el-table-column prop="status" label="资产状态" width="100" />
      <el-table-column prop="purchaseDate" label="采购时间" width="120"/>
      <el-table-column prop="warrantyExpiry" label="维保到期时间" width="120" />
      <el-table-column prop="price" label="价格" width="80" />
      <el-table-column prop="location" label="资产位置" />
      <el-table-column prop="bizIp" label="业务IP" />
      <el-table-column prop="ibmcIp" label="管理IP" />
      <el-table-column prop="custodian" label="资产负责人" width="80" />
      <el-table-column prop="createdAt" label="创建时间" width="200" />
      <el-table-column prop="updateAt" label="更新时间" width="200"/>
      <el-table-column label="操作" fixed="right" width="180">
        <template #default="scope"> <!-- 通过插槽的scope 来绑定行数据 scope.row可以获取到当前行的数据 --->
          <el-button type="primary" size="mini" @click="handleEditRow(scope.row)">编辑</el-button>
          <el-button type="danger" size="mini"  @click="deleteUser(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-if="selectedRow" class="detail-box">
      <h3>资产编号：{{ selectedRow.assetCode }}</h3>
      <el-tabs v-model="activeTab">
        <el-tab-pane label="硬件配置信息" name="hardware">
          <!-- 硬件详情组件或展示区域 -->
          <HardwareInfo :asset="selectedRow" />
        </el-tab-pane>

        <el-tab-pane label="维修信息" name="repair">
          <RepairInfo :assetId="selectedRow.id" />
        </el-tab-pane>

        <el-tab-pane label="维保信息" name="warranty">
          <WarrantyInfo :assetId="selectedRow.id" />
        </el-tab-pane>

        <el-tab-pane label="调拨信息" name="transfer">
          <TransferInfo :assetId="selectedRow.id" />
        </el-tab-pane>
      </el-tabs>
    </div>

  </div>
</template>
<script lang="ts" setup>
import { ref,reactive,onMounted,toRefs } from "vue"
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAssetsAllList,delAssetsHandler,addAssetsHandler } from "../../api/assets.js"
import {getDepartmentList} from "../../api/department.js"
import Add from "./Add.vue"
import HardwareInfo from "./tabs/HardwareInfo.vue"
import RepairInfo from "./tabs/RepairInfo.vue"
import WarrantyInfo from "./tabs/WarrantyInfo.vue"
import TransferInfo from "./tabs/TransferInfo.vue"
const tableData = ref([])
const loading = ref(true)
const dialogFormVisible = ref(false)
const searchCriteria = reactive({
        username: '',
        password: '',
        ad_user_id: ''
      })
const assetForm = reactive({
    assetCode: "",
    assetName: "",
    category: "",
    status: "",
    purchaseDate: "",
    warrantyExpiry: "",
    price: 0,
    location: "",
    bizIp: "",
    ibmcIp: "",
    custodian: ""
})
const filteredData = ref([])
const departmentdata= ref([])
const disabledUserId = ref("1")
const filterTableData=()=>{
  filteredData.value = tableData.value.filter(item => {
    return (
      (!searchCriteria.username || item.Username.includes(searchCriteria.username)) &&
      (!searchCriteria.password || item.Password.includes(searchCriteria.password)) &&
      (!searchCriteria.ad_user_id || item.Ad_user_id.includes(searchCriteria.ad_user_id))
    )
  })
}
// 添加资产
const handleAdd = () =>{
  
  //addUserHandler(data).then((response)=>{
  //    console.log("response=========:",response.data)
  //})
  //const data=await getDepartmentData()
  //console.log("data++++++++++++++++++++++++++++",data)
  //departmentdata.value=data
  dialogFormVisible.value=true
  console.log("department---------0807----------------")

}
// 删除用户
const deleteUser = (row) => {
  console.log("当前行的数据： ",row)
  ElMessageBox.confirm(
    row.username + '用户将被删除. 是否确认删除?',
    'Warning',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(() => {
    loading.value=true
    delUserHandler(row.id).then((response)=>{
      console.log("response=========:",response.data)
      
      ElMessage({
        type: 'success',
        message: 'Delete completed',
      })
      getUserInfo()
    }).catch((err)=>{
      console.log(err)
    })
    
  })
  .catch(() => {
    ElMessage({
      type: 'info',
      message: 'Delete canceled',
    })
  })
}
// 获取资产信息
const getAssetsInfo=()=>{
  getAssetsAllList().then((response)=>{
      const result= response.data.data
      if (result){
        const base64String = result.assetslist
        const decodedBytes = atob(base64String);
        // 将字节串转换为 Uint8Array
        const uint8Array = new Uint8Array(decodedBytes.split('').map(c => c.charCodeAt(0)));
        // 使用 TextDecoder 解码为字符串
        const decoder = new TextDecoder("utf-8");
        const decodedString = decoder.decode(uint8Array);
        console.log("assetsinfo",decodedString)
        // window.localStorage.setItem("menus",decodedString)
        // const md5Hash = md5(decodedString+'menus_list');
        // window.localStorage.setItem("md5Hash",md5Hash)

        // 存储菜单数据到 localStorage
        // const decodedString = window.localStorage.getItem('menus');
        tableData.value = JSON.parse(decodedString)
        if (filteredData.value.length==0) {
          filteredData.value = tableData.value
        } else {
          filterTableData()
        }
        loading.value=false
        // 返回解析后的菜单数据
        //return JSON.parse(decodedString);
      }
  }).catch((err)=>{
      console.log(err)
  })
}
// 获取部门数据
  const getDepartmentData=()=>{
      getDepartmentList().then((response)=>{
        const result = response.data.data
        if (result.departmentlist == '[]') {
                return [];
        } else {
            const base64String = result.departmentlist
            const decodedBytes = atob(base64String);
            // 将字节串转换为 Uint8Array
            const uint8Array = new Uint8Array(decodedBytes.split('').map(c => c.charCodeAt(0)));
            // 使用 TextDecoder 解码为字符串
            const decoder = new TextDecoder("utf-8");
            const decodedString = decoder.decode(uint8Array);
            console.log("departmentinfo===========+++++++++",decodedString)
            //window.localStorage.setItem("menus",decodedString)
            //const md5Hash = md5(decodedString+'menus_list');
            //window.localStorage.setItem("md5Hash",md5Hash)     
            departmentdata.value=JSON.parse(decodedString)
            //console.log("departmentinfo=======---------------------====+++++++++",departmentdata)
            // 存储菜单数据到 localStorage
            // const decodedString = window.localStorage.getItem('menus');
            // 返回解析后的菜单数据
            // return JSON.parse(decodedString);
        }
      })
  }
// 清空userForm表单数据
const clearassetForm = () => {
  Object.keys(assetForm).forEach(key => {
    userForm[key] = "";
  });
};

// 定义接收事件的函数
const handleSubmit = async (formData) => {
  try {
    // 在父组件中执行相应的逻辑，例如提交数据到后端
    console.log('接收到的表单数据：', formData);
    // 创建一个新对象，排除 "password" 属性
    // const { checkpass, ...newformData } = formData;
    // console.log("newformData=============",newformData)
    // newformData["department_name"]=newformData["department_name"].toString();
    const response = await addAssetsHandler(formData)
    if (response.data) {
       ElMessage({
            message: response.data.message,
            type: 'success',
          })
       await getAssetsInfo()
    } else {
      ElMessage({
            message: response.data.message,
            type: 'Error',
      })
    }
    dialogFormVisible.value=false
    console.log("assetForm=====+++++++",assetForm)
    clearUserForm()
    console.log("assetForm=====+++++++",assetForm)
    // 可以在这里做API请求等操作
    
  } catch(error){
    console.log(error)
  }
};

const selectedRow = ref(null)
const activeTab = ref('hardware')
const handleRowClick = (row) => {
  selectedRow.value = row
  console.log("selectedRow======20250808========",selectedRow.value)
  activeTab.value = 'hardware'
}
onMounted(()=>{
  getAssetsInfo()
  getDepartmentData()
})



</script>
<style scoped>
.main-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.el-table {
  flex: 1;
}
.detail-box {
  flex: 1;
  padding: 16px;
  border-top: 1px solid #eee;
  background: #f9f9f9;
  overflow-y: auto;
}
.search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}
.search-input {
  margin-left: 10px;
  width: 300px;
}
.table-actions {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-start;

}

</style>
